using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;
using System.Windows;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Collections.Generic;
using System.Windows.Controls;

namespace Tryit.ViewModels
{
    public class PersonManagementViewModel : BindableBase
    {
        private readonly ObservableCollection<string> _analystList;
        private readonly ObservableCollection<string> _verifierList;
        private ObservableCollection<string> _personList;
        private string _newPersonName;
        private DataGrid _dataGrid;

        public ObservableCollection<string> PersonList
        {
            get => _personList;
            set => SetProperty(ref _personList, value);
        }

        public string NewPersonName
        {
            get => _newPersonName;
            set
            {
                if (SetProperty(ref _newPersonName, value))
                {
                    (AddPersonCommand as DelegateCommand)?.RaiseCanExecuteChanged();
                }
            }
        }

        public DataGrid DataGrid
        {
            get => _dataGrid;
            set
            {
                if (SetProperty(ref _dataGrid, value))
                {
                    if (_dataGrid != null)
                    {
                        _dataGrid.SelectionChanged += DataGrid_SelectionChanged;
                    }
                }
            }
        }

        public ICommand AddPersonCommand { get; private set; }
        public ICommand DeletePersonCommand { get; private set; }
        public ICommand SaveCommand { get; private set; }

        public PersonManagementViewModel(ObservableCollection<string> analystList, ObservableCollection<string> verifierList)
        {
            _analystList = analystList;
            _verifierList = verifierList;
            _personList = new ObservableCollection<string>();
            
            // 从本地文件加载人员列表
            LoadPersonListFromFile();

            AddPersonCommand = new DelegateCommand(ExecuteAddPerson, CanExecuteAddPerson);
            DeletePersonCommand = new DelegateCommand(ExecuteDeletePerson, CanExecuteDeletePerson);
            SaveCommand = new DelegateCommand(ExecuteSave);
        }

        private void LoadPersonListFromFile()
        {
            try
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config");
                var filePath = Path.Combine(configPath, "persons.json");

                if (File.Exists(filePath))
                {
                    var json = File.ReadAllText(filePath);
                    var savedList = JsonSerializer.Deserialize<List<string>>(json);
                    
                    if (savedList != null)
                    {
                        _personList.Clear();
                        foreach (var person in savedList)
                        {
                            if (!_personList.Contains(person))
                            {
                                _personList.Add(person);
                            }
                        }
                    }
                }
                else
                {
                    // 如果文件不存在，使用传入的列表
                    foreach (var person in _analystList)
                    {
                        if (!_personList.Contains(person))
                        {
                            _personList.Add(person);
                        }
                    }
                    foreach (var person in _verifierList)
                    {
                        if (!_personList.Contains(person))
                        {
                            _personList.Add(person);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载人员列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            (DeletePersonCommand as DelegateCommand)?.RaiseCanExecuteChanged();
        }

        private bool CanExecuteAddPerson()
        {
            return !string.IsNullOrWhiteSpace(NewPersonName);
        }

        private void ExecuteAddPerson()
        {
            if (string.IsNullOrWhiteSpace(NewPersonName))
            {
                return;
            }

            if (!PersonList.Contains(NewPersonName))
            {
                PersonList.Add(NewPersonName);
                NewPersonName = string.Empty;
            }
            else
            {
                MessageBox.Show("该人员已存在", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        private bool CanExecuteDeletePerson()
        {
            return DataGrid?.SelectedItems != null && DataGrid.SelectedItems.Count > 0;
        }

        private void ExecuteDeletePerson()
        {
            if (DataGrid?.SelectedItems == null || DataGrid.SelectedItems.Count == 0)
            {
                return;
            }

            var result = MessageBox.Show($"确定要删除选中的 {DataGrid.SelectedItems.Count} 个人员吗？", "确认删除", 
                MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                var itemsToRemove = DataGrid.SelectedItems.Cast<string>().ToList();
                foreach (var person in itemsToRemove)
                {
                    PersonList.Remove(person);
                }
            }
        }

        private void ExecuteSave()
        {
            try
            {
                // 更新主窗口的列表
                _analystList.Clear();
                _verifierList.Clear();
                foreach (var person in PersonList)
                {
                    _analystList.Add(person);
                    _verifierList.Add(person);
                }

                // 保存到本地文件
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config");
                if (!Directory.Exists(configPath))
                {
                    Directory.CreateDirectory(configPath);
                }

                var filePath = Path.Combine(configPath, "persons.json");
                var json = JsonSerializer.Serialize(PersonList);
                File.WriteAllText(filePath, json);

                MessageBox.Show("保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
} 